package main

import (
	"gitee.com/yscsky/yu"
	"gitee.com/yscsky/yu/yuresp"
	"gitee.com/yscsky/yu/yusvr"
	"github.com/labstack/echo/v4"
	"github.com/labstack/echo/v4/middleware"
)

func main() {
	yu.Run(&app{
		name:    "EchoServer",
		echosvr: yusvr.NewEchoServer("echo", ":8000"),
	})
}

type app struct {
	name    string
	echosvr yusvr.IEchoServer
}

func (a *app) Name() string {
	return a.name
}

func (a *app) OnStart() bool {
	a.echosvr.Health()
	a.echosvr.Promethous("admin", "admin")
	g := a.echosvr.Group("/api", a.echosvr.NoCache(), a.echosvr.PromeMetrics(), middleware.Logger())
	g.GET("/getjson", a.getJson)
	g.GET("/getjsonauth", a.getJsonAuth, a.echosvr.BasicAuth("admin", "123456"))
	g.POST("/postjson", a.postJson)
	g.POST("/postjsonauth", a.postJsonAuth, a.echosvr.BasicAuth("admin", "123456"))
	g.POST("/postform", a.postForm)
	g.POST("/postformauth", a.postFormAuth, a.echosvr.BasicAuth("admin", "123456"))
	return true
}

func (a *app) OnStop() {}

func (a *app) Servers() []yu.IServer {
	return []yu.IServer{a.echosvr}
}

func (a *app) getJson(c echo.Context) error {
	defer yu.Cost("getJson")()
	return a.echosvr.JsonOK(c, "get json")
}

func (a *app) getJsonAuth(c echo.Context) error {
	defer yu.Cost("getJsonAuth")()
	return a.echosvr.JsonOK(c, "get json with auth")
}

func (a *app) postJson(c echo.Context) error {
	defer yu.Cost("postJson")()
	var req yuresp.Resp[string]
	if err := c.Bind(&req); err != nil {
		return a.echosvr.JsonErr(c, err)
	}
	return a.echosvr.JsonOK(c, req.Data)
}

func (a *app) postJsonAuth(c echo.Context) error {
	defer yu.Cost("postJsonAuth")()
	var req yuresp.Resp[string]
	if err := c.Bind(&req); err != nil {
		return a.echosvr.JsonErr(c, err)
	}
	return a.echosvr.JsonOK(c, req.Data)
}

func (a *app) postForm(c echo.Context) error {
	defer yu.Cost("postForm")()
	data := c.FormValue("data")
	if data == "" {
		return a.echosvr.JsonMsg(c, "data not found")
	}
	return a.echosvr.JsonOK(c, data)
}

func (a *app) postFormAuth(c echo.Context) error {
	defer yu.Cost("postFormAuth")()
	data := c.FormValue("data")
	if data == "" {
		return a.echosvr.JsonMsg(c, "data not found")
	}
	return a.echosvr.JsonOK(c, data)
}
